package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    //注入mongo
    @Autowired
    MongoTemplate mongoTemplate;

    //注入行为远程调用接口
    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 异步执行保存用户的搜索历史记录
     * @param dto
     */
    @Async("taskExecutor")//异步执行
    @Override
    public void insert(UserSearchDTO dto) {
        //1 参数检查
        //拿出搜索关键字
        String searchWords = dto.getSearchWords();
        //拿出entryId
        Integer entryId = dto.getEntryId();
        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId
                            (entryId, dto.getEquipmentId());

        //判断状态码
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用接口BehaviorFeign失败");
        }
        //拿到行为实体对象
        ApBehaviorEntry behaviorEntry = result.getData();

        if (behaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有该行为实体");
        }
        log.info("ApUserSearchServiceImpl insert entryId:{}, searchWords:{}", entryId, searchWords);
        //3 查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria
                .where("entryId").is(behaviorEntry.getId())
                .and("keyword").is(searchWords)), ApUserSearch.class);

        //3.1 存在则更新最新时间，更新状态
        if (apUserSearch!=null) {
            apUserSearch.setCreatedTime(new Date());

        }else {
            //3.2 不存在则新增
            //创建新的对象
            apUserSearch=new ApUserSearch();
            //设置行为实体id
            apUserSearch.setEntryId(behaviorEntry.getId());
            //设置搜索记录
            apUserSearch.setKeyword(searchWords);
            //设置创建时间
            apUserSearch.setCreatedTime(new Date());
        }
        //保存
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 查询用户搜索历史记录  显示10条
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        //检查参数, 给时间设置初始值 new Date()
        if (dto.getMinBehotTime()==null) {
            dto.setMinBehotTime(new Date());
        }

        //设置显示条数size为10
        int size =10;
        //拿到用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        //远程调用行为服务 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign
                .findByUserIdOrEquipmentId(user == null ? null : user.getId()
                        , dto.getEquipmentId());
        //判断状态码
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为实体接口失败");
        }
        //拿出数据
        ApBehaviorEntry entry = result.getData();
        //判断是否为空  为空则报错
        if (entry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有找到该行为实体");
        }
        //如果不为空, 则 查询当前用户的搜索列表, 按照时间降序排序 ,截取 dto的size
        List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria
                .where("entryId").is(entry.getId())
                .and("createdTime").lt(dto.getMinBehotTime()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size), ApUserSearch.class);
        //返回最终结果
            return  ResponseResult.okResult(searchList);

    }

    /**
     * 删除用户历史搜索记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        //根据行为实体id删除历史记录
        mongoTemplate.remove(Query.query(Criteria.where("_id")
                .is(dto.getId()))
                ,ApUserSearch.class);
        //返回删除成功结果
        return ResponseResult.okResult();
    }
}